<?php  if ( ! defined('BASEPATH')) exit('No direct script access allowed');

if ( ! function_exists('mb_substr'))
{
	function mb_substr($str,$start,$length = 0,$encoding = null)
	{
		if($length == 0) return $str; 
		
		if($encoding == null)
		{
			return substr($str, $start,$length);
		} 
		$str_length = strlen($str);
		$encoding = strtolower($encoding); 
		
		if ($encoding == 'utf8') {
			$l = 0;$i = 0;$length = 2*$length; 
			while ($i < $str_length) {
				if (ord($str{$i}) < 0x80) {
					$l++; $i++;
				} else if (ord($str{$i}) < 0xe0) {
					$l++; $i += 2;
				} else if (ord($str{$i}) < 0xf0) {
					$l += 2; $i += 3;
				} else if (ord($str{$i}) < 0xf8) {
					$l += 1; $i += 4;
				} else if (ord($str{$i}) < 0xfc) {
					$l += 1; $i += 5;
				} else if (ord($str{$i}) < 0xfe) { 
					$l += 1; $i += 6;
				}
				if ($l > $length) {
					$newstr = substr($str, 0, $i);
					break;
				}
			}
			if($l <= $length) {
				return $str;
			}
		}
		elseif($encoding == 'gbk') 
		{
			if ($length >= $str_length) 
			{
				return $str;
			}
			while ($i <= $str_length) 
			{
				if (ord($str{$i}) > 0xa0) 
				{
					$l += 2; $i += 2;
				} else {
					$l++; $i++;
				}
		
				if ($l >= $length) {
					$newstr = substr($str, 0, $i);
					break;
				}
			}
		}
		
		return $newstr;
	}
}   

if ( ! function_exists('mb_strlen'))
{
	function mb_strlen($str,$encoding = null)
	{
		if($encoding == null)
		{
			return strlen($str);
		}
		$str_length = strlen($str);
		$encoding = strtolower($encoding);
	
		if ($encoding == 'utf8') {   
			$l = 0;$i = 0;$len=0;
			while ($i < $str_length) {
				if (ord($str{$i}) < 0x80) {
					$l++; $i++;$len ++;
				} else if (ord($str{$i}) < 0xe0) {
					$l++; $i += 2;$len ++;
				} else if (ord($str{$i}) < 0xf0) {
					$l += 2; $i += 3;$len ++;
				} else if (ord($str{$i}) < 0xf8) {
					$l += 1; $i += 4;$len ++;
				} else if (ord($str{$i}) < 0xfc) {
					$l += 1; $i += 5;$len ++;
				} else if (ord($str{$i}) < 0xfe) {
					$l += 1; $i += 6;$len ++;
				}
			}
			return $len;
		}
		elseif($encoding == 'gbk')
		{
			$len = 0;
			while ($i <= $str_length)
			{
				if (ord($str{$i}) > 0xa0)
				{
					$l += 2; $i += 2;$len++;
				} else {
					$l++; $i++;$len++;
				}
			}
		}
	
		return $len;
	}
}    